<template>
  <div class="payment">
    <el-card>
      <template #header>
        <span>费用支付</span>
      </template>

      <el-table :data="orders" style="width: 100%">
        <el-table-column prop="orderNum" label="订单号"/>
        <el-table-column prop="dormitory" label="宿舍楼"/>
        <el-table-column prop="roomNum" label="房间号"/>
        <el-table-column prop="totalAmount" label="金额">
          <template #default="scope">
            ¥{{ scope.row.totalAmount }}
          </template>
        </el-table-column>
        <el-table-column prop="type" label="状态">
          <template #default="scope">
            <el-tag :type="scope.row.type === '已支付' ? 'success' : 'warning'">
              {{ scope.row.type }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="orderTime" label="创建时间">
          <template #default="scope">
            {{ formatDate(scope.row.orderTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button
                v-if="scope.row.type === '未支付'"
                type="primary"
                size="small"
                @click="payOrder(scope.row)"
            >
              支付
            </el-button>
            <span v-else class="paid-label">已支付</span>
          </template>
        </el-table-column>
      </el-table>

      <div v-if="orders.length === 0" class="empty-state">
        <el-empty description="暂无订单"/>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import {ref, onMounted} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import request from '../../utils/request'

const orders = ref([])

const formatDate = (dateString) => {
  return new Date(dateString).toLocaleString()
}

const loadOrders = async () => {
  try {
    const response = await request.get('/api/order/my')
    if (response.data.code === 200) {
      orders.value = response.data.data
    }
  } catch (error) {
    console.error('加载订单失败:', error)
  }
}

const payOrder = async (order) => {
  try {
    await ElMessageBox.confirm(
        `确定支付订单 ${order.orderNum} 吗？金额：¥${order.totalAmount}`,
        '确认支付',
        {
          confirmButtonText: '确定支付',
          cancelButtonText: '取消',
          type: 'warning'
        }
    )

    const response = await request.put(`/api/order/pay/${order.orderNum}`)
    if (response.data.code === 200) {
      ElMessage.success('支付成功')
      await loadOrders()
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('支付失败')
    }
  }
}

onMounted(() => {
  loadOrders()
})
</script>

<style scoped>
.payment {
  padding: 20px;
}

.paid-label {
  color: #67C23A;
  font-weight: bold;
}

.empty-state {
  text-align: center;
  padding: 40px 0;
}
</style>
